/*
 * check TSC synchronization.
 *
 * Copyright (C) 2006, Red Hat, Inc., Ingo Molnar
 *
 * We check whether all boot CPUs have their TSC's synchronized,
 * print a warning if not and turn off the TSC clock-source.
 *
 * The warp-check is point-to-point between two CPUs, the CPU
 * initiating the bootup is the 'source CPU', the freshly booting
 * CPU is the 'target CPU'.
 *
 * Only two CPUs may participate - they can enter in any order.
 * ( The serial nature of the boot logic and the CPU hotplug lock
 *   protects against more than 2 CPUs entering this code. )
 */
#include <linux/module.h>
#include <linux/init.h>
#include <linux/version.h>
#include <linux/spinlock.h>
#include <linux/kernel.h>
#include <linux/smp.h>
#include <linux/nmi.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/kallsyms.h>
#include <asm/uaccess.h>
#include <asm/tsc.h>

/*
 * default do force tsc sync if use this ko
 */
static unsigned long long cpu_core_tsc_offset[NR_CPUS];
static bool only_check_tsc;
static bool default_tsc_sync = true;

static struct proc_dir_entry *tsc_sync_proc_entry;
#define TSC_SYNC_PROC_FILE		"force_tsc_sync"

/*
 * Entry/exit counters that make sure that both CPUs
 * run the measurement code at once:
 */
static atomic_t start_count;
static atomic_t stop_count;

/*
 * We use a raw spinlock in this exceptional case, because
 * we want to have the fastest, inlined, non-debug version
 * of a critical section, to be able to prove TSC time-warps:
 */
static arch_spinlock_t sync_lock = __ARCH_SPIN_LOCK_UNLOCKED;

static cycles_t last_tsc;
static cycles_t max_warp;
static int nr_warps;

/*
 * TSC-warp measurement loop running on both CPUs:
 */
static void check_tsc_warp(unsigned int timeout)
{
	cycles_t start, now, prev, end;
	int i;
	start = rdtsc_ordered();
	barrier_nospec();
	/*
	 * The measurement runs for 'timeout' msecs:
	 */
	end = start + (cycles_t) tsc_khz * timeout;
	now = start;

	for (i = 0; ; i++) {
		/*
		 * We take the global lock, measure TSC, save the
		 * previous TSC that was measured (possibly on
		 * another CPU) and update the previous TSC timestamp.
		 */
		arch_spin_lock(&sync_lock);
		prev = last_tsc;
		now = rdtsc_ordered();
		barrier_nospec();
		last_tsc = now;
		arch_spin_unlock(&sync_lock);

		/*
		 * Be nice every now and then (and also check whether
		 * measurement is done [we also insert a 10 million
		 * loops safety exit, so we dont lock up in case the
		 * TSC readout is totally broken]):
		 */
		if (unlikely(!(i & 7))) {
			if (now > end || i > 10000000)
				break;
			cpu_relax();
			touch_nmi_watchdog();
		}
		/*
		 * Outside the critical section we can now see whether
		 * we saw a time-warp of the TSC going backwards:
		 */
		if (unlikely(prev > now)) {
			arch_spin_lock(&sync_lock);
			max_warp = max(max_warp, prev - now);
			nr_warps++;
			arch_spin_unlock(&sync_lock);
		}
	}
	WARN(!(now-start),
		"Warning: zero tsc calibration delta: %Ld [max: %Ld]\n",
			now-start, end-start);
}

/*
 * If the target CPU coming online doesn't have any of its core-siblings
 * online, a timeout of 20msec will be used for the TSC-warp measurement
 * loop. Otherwise a smaller timeout of 2msec will be used, as we have some
 * information about this socket already (and this information grows as we
 * have more and more logical-siblings in that socket).
 *
 * Ideally we should be able to skip the TSC sync check on the other
 * core-siblings, if the first logical CPU in a socket passed the sync test.
 * But as the TSC is per-logical CPU and can potentially be modified wrongly
 * by the bios, TSC sync test for smaller duration should be able
 * to catch such errors. Also this will catch the condition where all the
 * cores in the socket doesn't get reset at the same time.
 */
static inline unsigned int loop_timeout(int cpu)
{
	return (cpumask_weight(topology_core_cpumask(cpu)) > 1) ? 2 : 20;
}

/*
 * Source CPU calls into this - it waits for the freshly booted
 * target CPU to arrive and then starts the measurement:
 */
static void _check_tsc_sync_source(int cpu)
{
	int cpus = 2;

	/*
	 * Reset it - in case this is a second bootup:
	 */
	atomic_set(&stop_count, 0);

	/*
	 * Wait for the target to arrive:
	 */
	while (atomic_read(&start_count) != (cpus - 1))
		cpu_relax();
	/*
	 * Trigger the target to continue into the measurement too:
	 */
	atomic_inc(&start_count);

	check_tsc_warp(loop_timeout(cpu));

	while (atomic_read(&stop_count) != cpus-1)
		cpu_relax();

	if (nr_warps) {
		pr_warn("TSC synchronization [CPU#%d -> CPU#%d]:\n",
			smp_processor_id(), cpu);
		pr_warn("Measured %Ld cycles TSC warp between CPUs, "
			   "turning off TSC clock.\n", max_warp);

		cpu_core_tsc_offset[cpu] = max_warp;
	} else {
		pr_debug("TSC synchronization [CPU#%d -> CPU#%d]: passed\n",
			smp_processor_id(), cpu);
	}

	/*
	 * Reset it - just in case we boot another CPU later:
	 */
	atomic_set(&start_count, 0);
	nr_warps = 0;
	max_warp = 0;
	last_tsc = 0;

	/*
	 * Let the target continue with the bootup:
	 */
	atomic_inc(&stop_count);
}

/*
 * Freshly booted CPUs call into this:
 */
static void _check_tsc_sync_target(void)
{
	int cpus = 2;

	/*
	 * Register this CPU's participation and wait for the
	 * source CPU to start the measurement:
	 */
	atomic_inc(&start_count);
	while (atomic_read(&start_count) != cpus)
		cpu_relax();

	check_tsc_warp(loop_timeout(smp_processor_id()));

	/*
	 * Ok, we are done:
	 */
	atomic_inc(&stop_count);

	/*
	 * Wait for the source CPU to print stuff:
	 */
	while (atomic_read(&stop_count) != cpus)
		cpu_relax();
}


#define TSC_SYNC_MASTER_CPU		0
/*
 * calibrate cpu tsc value based on offset
 */
static void fix_tsc_sync_offset(void)
{
	int cpu = smp_processor_id();
	unsigned long long tsc;

	tsc = rdtsc_ordered() + cpu_core_tsc_offset[cpu];
	barrier_nospec();
	write_tsc(tsc & 0xFFFFFFFF, (tsc >> 32) & 0xFFFFFFFF);
}

static void smp_call_check_tsc_sync_target(void *info)
{
	unsigned long flags;

	preempt_disable();
	local_irq_save(flags);
	_check_tsc_sync_target();

	if (!only_check_tsc)
		fix_tsc_sync_offset();

	local_irq_restore(flags);
	preempt_enable();
}

static void force_tsc_sync_on_master_cpu(void)
{
	unsigned long flags;
	int master_cpu;
	int cpu;

	preempt_disable();

	master_cpu = smp_processor_id();
	if (master_cpu != TSC_SYNC_MASTER_CPU) {
		preempt_enable();
		printk(KERN_ERR"only support cpu tsc sync on cpu0\n");
		return;
	}

	for_each_online_cpu(cpu) {
		if (cpu == master_cpu)
			continue;
		smp_call_function_single(cpu, smp_call_check_tsc_sync_target, 0, 0);
		local_irq_save(flags);
		_check_tsc_sync_source(cpu);
		local_irq_restore(flags);
	}

	preempt_enable();
}

static void trigger_force_tsc_sync(void)
{
	unsigned long ret;
	long (*sched_setaff)(pid_t pid, const struct cpumask *in_mask);
	cpumask_var_t mask;
	long sched_ret;

	ret = find_trustlist_symbols("sched_setaffinity");
	if (ret == 0) {
		pr_err("trigger_force_tsc_sync: find symbol(sched_setaffinity) failed\n");
		return;
	}
	sched_setaff = (long (*)(pid_t, const struct cpumask *))(uintptr_t)ret;

	if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
		pr_err("trigger_force_tsc_sync: allock mask fail\n");
		return;
	}

	/* always use cpu0 as master cpu for tsc sync */
	cpumask_set_cpu(0, mask);
	sched_ret = sched_setaff(0, mask);
	free_cpumask_var(mask);
	if (sched_ret != 0) {
		pr_err("trigger_force_tsc_sync: sched_setaffinity to cpu0 failed with error %d\n",
				sched_ret);
		return;
	}

	force_tsc_sync_on_master_cpu();
}

/*
* proc handler callback
*/
static int tsc_sync_proc_show(struct seq_file *m, void *v)
{
	int cpu;

	for_each_online_cpu(cpu) {
		seq_printf(m, "[cpu%2d] tsc_offset is: %lld\n", cpu, cpu_core_tsc_offset[cpu]);
	}

	return 0;
}

static int proc_show_open(struct inode *inode, struct file *file)
{
	return single_open(file, tsc_sync_proc_show, NULL);
}

static ssize_t proc_show_write(struct file *file, const char __user *buf, size_t count, loff_t *offs)
{
	trigger_force_tsc_sync();

	return count;
}

static const struct proc_ops tsc_sync_proc_fops = {
	.proc_open = proc_show_open,
	.proc_read = seq_read,
	.proc_write = proc_show_write,
	.proc_lseek = seq_lseek,
	.proc_release = single_release,
};

static int __init tsc_sync_init(void)
{
	if (default_tsc_sync) {
		trigger_force_tsc_sync();
	}

	tsc_sync_proc_entry = proc_create(TSC_SYNC_PROC_FILE, 0640, NULL, &tsc_sync_proc_fops);
	if (!tsc_sync_proc_entry) {
		printk(KERN_ERR "create proc entry failed\n");
	}

	return 0;
}

static void __exit tsc_sync_exit(void)
{
	if (tsc_sync_proc_entry) {
		remove_proc_entry(TSC_SYNC_PROC_FILE, NULL);
	}

	return;
}

module_init(tsc_sync_init);
module_exit(tsc_sync_exit);

MODULE_IMPORT_NS(HW_RTOS_NS);

module_param(only_check_tsc, bool, 0640);
MODULE_PARM_DESC(only_check_tsc, "only check tsc offset, donot writeback to hardware");

module_param(default_tsc_sync, bool, 0640);
MODULE_PARM_DESC(default_tsc_sync, "auto trigger tsc sync when insmod module");

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("tsc_sync_for_mbsc[a] board, donot use for b_board");
